
import bson
from wtforms import fields
from flask import g
from app.validators import PageForm, BaseForm
from app.errors import ParameterError


class QueryBasePageForm(PageForm):

    uid = fields.StringField()
    target_name = fields.StringField()
    target_url = fields.StringField()

    def validate_uid(self, value):
        if g.role.name != '管理员':
            return
        if not value.data:
            raise ParameterError(msg="请选择用户")
        try:
            self.uid = bson.ObjectId(value.data)
        except bson.errors.BSONError:
            raise ParameterError(msg="用户数据错误")


class UpdateBasePageForm(BaseForm):
    task_ids = fields.FieldList(fields.StringField())

    def validate_task_ids(self, task_ids):
        task_ids = task_ids.data
        if not task_ids:
            raise ParameterError(msg="没有选择任务样本")
        if len(set(task_ids)) > 50:
            raise ParameterError(msg="一次最多支持更新50个资产样本")
